<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <span slot="before">共{{ params.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
          >导入</el-button>
          <el-button
            size="small"
            type="danger"
            @click="exportExcel"
          >导出</el-button>
          <el-button
            size="small"
            type="primary"
            @click="addEmployee"
          >新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment">
            <template #default="{ row }">
              {{ row.formOfEmployment | FormatEmployment }}
            </template>
          </el-table-column>
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="{ row }">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :page-size="params.size"
            :current-page="params.page"
            :total="params.total"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工模态框 -->
      <Addemployee
        :show-dialog.sync="addDialog"
        @refreshEmployeeList="refreshEmployeeList"
      />
      <!-- 编辑角色模态框 -->
      <AssginRole ref="AssginRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import AssginRole from './components/assign-role.vue'
import { delEmployee, getEmployeeList } from '@/api/employees'
import Employees from '@/api/constant/employees'
import Addemployee from './components/add-employee.vue'
import { formatDate } from '@/filters'
export default {
  components: { Addemployee, AssginRole },
  filters: {
    // 格式化聘用形式
    FormatEmployment(val) {
      const obj = Employees.hireType.find((item) => item.id === +val)
      return obj ? obj.value : '未知'
    }
  },
  data() {
    return {
      params: {
        page: 1, // 当前页码
        size: 5,
        total: 0 // 总数
      },
      employeeList: [],
      addDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 获取列表数据
    async getEmployeeList() {
      const res = await getEmployeeList(this.params)
      // console.log(res)
      this.employeeList = res.rows.map((item) => ({ ...item, enableState: 1 }))
      this.params.total = res.total
    },
    // 切换分页
    currentChange(val) {
      this.params.page = val
      this.getEmployeeList()
    },
    // 删除员工
    async delEmployee(id) {
      await this.$confirm('确定要删除嘛？')
      await delEmployee(id)
      this.$message.success('操作成功')
      if (this.employeeList.length === 1 && this.params.page > 1) {
        this.params.page--
      }
      this.getEmployeeList()
    },
    // 新增员工
    addEmployee() {
      this.addDialog = true
    },
    // 新增员工完毕
    refreshEmployeeList() {
      // 返回最后一页
      this.params.page = Math.ceil((this.params.total + 1) / this.params.size)
      // 刷新数据
      this.getEmployeeList()
      // 关闭模态框
      this.addDialog = false
    },
    // 导出Excel
    async exportExcel() {
      // 获取所有员工信息
      const { rows } = await getEmployeeList({
        page: 1,
        size: this.params.total
      })
      console.log(rows)
      const dict = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const header = Object.keys(dict)
      console.log(header)
      const data = rows.map((user) => {
        return this.obj2arr(user, dict)
      })
      console.log(data)
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      export_json_to_excel({
        header, // 表头 必填
        data // 具体数据 必填
      })
    },
    obj2arr(user, dict) {
      const data = []
      for (const key in dict) {
        const newKey = dict[key]
        const newVal = user[newKey]
        if (newKey === 'formOfEmployment') {
          //  枚举格式化聘用形式
          const obj = Employees.hireType.find((item) => item.id === +newVal)
          data.push(obj ? obj.value : '未知')
        } else if (newKey === 'timeOfEntry' || newKey === 'correctionTime') {
          data.push(formatDate(newVal))
        } else {
          data.push(newVal)
        }
      }
      return data
    },
    // 编辑角色权限
    async editRole(id) {
      this.userId = id
      // 回显数据后才打开模态框
      await this.$refs.AssginRole.getUserInfoById(id)
      this.showRoleDialog = true
    }
  }
}
</script>

<style>
</style>
